package com.jplus.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
//import io.goeasy.GoEasy;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JsonUtils {
    /**
     * 将Java对象转化为JSON字符串
     *
     * @param obj
     * @return
     * @throws IOException
     */
    public static String getJSON(Object obj) throws IOException {
        if (null == obj) {
            return "";
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 将JSON字符串转化为Java对象
     *
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getObj(String json, TypeReference<T> ref)
            throws IOException {
        if (null == json || json.length() == 0) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return (T) mapper.readValue(json, ref);
    }

    public static Object getObj(String json, Class pojoClass) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, pojoClass);
    }


    public static void main(String[] args) throws Exception {

//        User user = new User();
//        user.setPassword("0000");
//        user.setUsername("田钦政");
//        user.setNickName("ittqqzz");
//        user.setAdmin(1);
//        user.setStatus(1);
//        user.setLastLoginIp("192.168.0.1");
//        user.setLoginIp("192.168.0.2");
//        user.setLoginNum(15);
//        user.setLoginTime(new Date());
//        user.setLastLoginTime(new Date());
//        String json=getJSON(user);
//        System.out.println(json);

//        GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io/publish", "BC-79e2545c6c9c4d7984ebdc99755052ba");
//        goEasy.publish("order_push", "123");

        /*
        注意无法解析前端发送的日期，因为他是字符串格式的
         */
//        String j = "{\"id\":null,\"username\":\"田钦政\",\"password\":\"0000\",\"nickName\":\"ittqqzz\",\"phone\":null," +
//                "\"status\":1,\"admin\":1,\"loginNum\":15,\"loginIp\":\"192.168.0.2\",\"lastLoginIp\":\"192.168.0.1\"," +
//                "\"authCode\":null,\"businessId\":null,\"registerTime\":null,\"registerIp" +
//                "\":null,\"order\":null,\"comments\":null}";
//        User u = (User) getObj(j, User.class);
//        System.out.println(u.toString());

    }
}
